<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" append-to-body width="850px">
		<el-form ref="form" size="medium" :model="userFrom" :rules="userRules" label-width="90px" validate-on-rule-change class="user_form_wrapper">
			<el-row :gutter="30" v-loading="loading">
				<el-col :span="12">
					<el-form-item label="用户姓名" prop="userName">
						<el-input v-model="userFrom.userName" placeholder="请输入用户昵称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="电子邮箱" prop="account">
						<!-- <sw-letter-input v-model="userFrom.account" placeholder="请输入电子邮箱"></sw-letter-input> -->
						<el-input v-model="userFrom.account" placeholder="请输入电子邮箱"></el-input>
					</el-form-item>
				</el-col>
				<template v-if="addOrEdit">
					<el-col :span="12">
						<el-form-item label="用户密码" prop="password">
							<el-input v-model="userFrom.password" show-password placeholder="请输入用户密码"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="确认密码" prop="confirmpass">
							<el-input v-model="userFrom.confirmpass" show-password placeholder="请输入确认密码"></el-input>
						</el-form-item>
					</el-col>
				</template>
				<el-col :span="12">
					<el-form-item label="出生日期" prop="birthDate">
						<el-date-picker v-model="userFrom.birthDate" type="date" placeholder="请选择出生日期" value-format="yyyy-MM-dd" style="width: 100%"></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户民族" prop="ethnic">
						<nation-select v-model="userFrom.ethnic" placeholder="请选择用户民族" style="width: 100%"></nation-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="联系电话" prop="phone">
						<sw-number-input v-model="userFrom.phone" maxLength="11" placeholder="请输入联系电话"></sw-number-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户职称" prop="filed1">
						<sw-dict-select v-model="userFrom.filed1" dict-name="USER_POST" placeholder="请选择用户职称" style="width: 100%" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户单位" prop="filed2">
						<el-input v-model="userFrom.filed2" placeholder="输入用户单位"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="单位类型" prop="filed3">
						<el-select v-model="userFrom.filed3" placeholder="请选择单位类型" style="width: 100%">
							<el-option v-for="(item, index) in dictEnums['DEPART_TYPE']" :key="index" :label="item.content" :value="item.content" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="单位属性" prop="filed4">
						<el-select v-model="userFrom.filed4" placeholder="选择单位属性" style="width: 100%">
							<el-option v-for="(item, index) in dictEnums['DEPART_ATTRS']" :key="index" :label="item.content" :value="item.content" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户角色" prop="role">
						<el-select v-model="userFrom.role" placeholder="请选择用户角色" popper-class="user_role_select" style="width: 100%">
							<el-option-group v-for="(group, index) in roleGroupData" :key="index" :label="group.label">
								<el-option v-for="item in group.children" :key="item.value" :label="item.name" :value="item.id"></el-option>
							</el-option-group>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户性别" prop="sex">
						<el-radio-group v-model="userFrom.sex">
							<el-radio v-for="(item, index) in dictEnums['USER_SEX']" :key="index" :label="item.value">{{ item.msg }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<!-- <el-col :span="11">
					<el-form-item label="用户类型" prop="type">
						<el-radio-group v-model="userFrom.type">
							<el-radio v-for="(item, index) in dictEnums['USER_TYPE']" :key="index" :label="item.value">{{ item.msg }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="13">
					<el-form-item label="用户系统类型" prop="userType" label-width="120px">
						<el-select v-model="userFrom.userType" placeholder="请选择用户系统类型" style="width: 100%">
							<el-option label="可登录" value="1"></el-option>
							<el-option label="可调用外部接口" value="2"></el-option>
							<el-option label="可登录+可调用外部接口" value="3"></el-option>
						</el-select>
					</el-form-item>
				</el-col> -->
				<!-- <template v-if="userFrom.type === '2'">
					<el-col :span="12">
						<el-form-item label="班级编号" prop="classNo">
							<el-input v-model="userFrom.classNo" placeholder="输入编辑编号"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="专业编号" prop="major">
							<el-input v-model="userFrom.major" placeholder="输入专业编号"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="入学年月" prop="entranceDate">
							<el-date-picker v-model="userFrom.entranceDate" type="month" placeholder="入学年月"></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="生源地" prop="source">
							<el-input v-model="userFrom.source" placeholder="输入生源地"></el-input>
						</el-form-item>
					</el-col>
				</template> -->
			</el-row>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="btnLoading" @click="handleSubmitUser">确定</el-button>
		</template>
	</el-dialog>
</template>

<script>
import rsa from '@/utils/rsa';
import { mapGetters } from 'vuex';
import nationSelect from '@/components/nationSelect';
import { getRoleList } from '@/api/system/tbSysRole';
import { userDetail, addedUser, updateUser, auditUser } from '@/api/system/tbSysUser';
export default {
	components: { nationSelect },
	props: {
		userId: String,
		value: { type: Boolean, default: false },
		departData: { type: Array, default: () => [] }
	},
	data() {
		const passRule = this.$getPassRules();
		const passValidator = (rule, value, callback) => {
			if (!this.userFrom.password) {
				callback(new Error('请输入用户密码'));
			} else if (this.userFrom.password !== value) {
				callback(new Error('用户密码和确认密码不一致'));
			} else {
				callback();
			}
		};
		return {
			loading: false,
			visible: this.value,
			userFrom: {},
			userRules: {
				account: [
					{ required: true, message: '请输入电子邮箱', trigger: 'blur' },
					{ type: 'email', message: '请输入正确的电子邮箱', trigger: 'blur' }
				],
				userName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
				password: [
					{ required: true, message: '请输入用户密码', trigger: 'blur' },
					{ pattern: passRule.rules, message: passRule.message, trigger: 'blur' }
				],
				confirmpass: [
					{ required: true, message: '请输入确认密码', trigger: 'blur' },
					{ validator: passValidator, trigger: 'blur' }
				],
				phone: [
					{ required: true, message: '请输入联系电话', trigger: 'blur' },
					{ pattern: /^((0\d{2,3}-\d{7,8})|(1[3-9]\d{9}))$/, message: '电话号码格式不正确', trigger: 'blur' }
				],
				role: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
				filed1: [{ required: true, message: '请选择用户职称', trigger: 'change' }],
				filed2: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
				filed3: [{ required: true, message: '请选择单位类型', trigger: 'change' }],
				filed4: [{ required: true, message: '请选择单位属性', trigger: 'change' }]
			},
			roleListData: [],
			roleGroupData: [],
			defaultProps: {
				label: 'name',
				children: 'childList'
			},
			btnLoading: false
		};
	},
	computed: {
		...mapGetters(['dictEnums', 'siteInfo']),
		addOrEdit() {
			return !this.userId;
		},
		dialogTitle() {
			return this.addOrEdit ? '新增用户' : '修改用户';
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.$nextTick(async () => {
				this.$refs['form'].resetFields();
				if (this.addOrEdit) {
					this.userFrom = {};
				} else {
					this.loading = true;
					await this.getUserDetail();
					this.loading = false;
				}
			});
		},
		roleListData(arr) {
			this.roleGroupData = this.dictEnums['ROLE_TYPE'].map((item) => {
				let typeRoleArr = arr.filter((n) => n.type === item.value);
				let checkedRoleArr = typeRoleArr.filter((n) => !!n.checked).map((n) => n.id);
				return { label: item.msg, value: item.value, children: typeRoleArr };
			});
		}
	},
	mounted() {
		this.getRoleData();
	},
	methods: {
		//获取角色数据
		async getRoleData() {
			let params = { page: 1, limit: 9999 };
			let result = await getRoleList(params).then((res) => res.data);
			if (result.code === '0') {
				this.roleListData = !result.data ? [] : result.data;
			}
		},

		//获取用户详情
		async getUserDetail() {
			let result = await userDetail(this.userId).then((res) => res.data);
			if (result.code === '0') {
				let datas = !result.data ? {} : result.data[0];
				let role = !datas.roleList[0] ? '' : datas.roleList[0].id;
				this.userFrom = { ...datas, role };
			}
		},

		//提交
		async handleSubmitUser() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				this.addOrEdit ? await this.addedUserRequest() : await this.updateUserRequest();
				this.btnLoading = false;
			});
		},

		//格式化添加参数
		formatAddParams() {
			let params = this.$lodash.cloneDeep(this.userFrom);
			params['type'] = '2';
			params['systemKey'] = '1';
			params['picId'] = '-1';
			params['deptId'] = '-1';
			params['diskSpace'] = 0;
			params['userType'] = '1';
			params['password'] = rsa.rsaPublicData(params.password);
			return params;
		},

		//添加用户请求
		async addedUserRequest() {
			let params = this.formatAddParams();
			let result = await addedUser(params).then((res) => res.data);
			if (result.code === '0') {
				this.$showCustomMessage('success', `添加用户成功`);
				this.auditUserRequest(result.data[0].id);
				this.visible = false;
				this.$emit('refresh');
			}
		},

		//更新用户请求
		async updateUserRequest() {
			let params = { ...this.userFrom };
			let result = await updateUser(params).then((res) => res.data);
			if (result.code === '0') {
				this.$showCustomMessage('success', `修改用户成功`);
				this.auditUserRequest(params.id);
				this.visible = false;
				this.$emit('refresh');
			}
		},

		//格式化审核参数
		formatAuditParams(id) {
			let datas = this.$lodash.cloneDeep(this.userFrom);
			let params = { id, del: '1', filed3: datas.filed3, filed4: datas.filed4 };
			params['proleList'] = [{ relId: datas.role, operType: '1' }];
			return params;
		},

		//审核用户
		async auditUserRequest(id) {
			let params = this.formatAuditParams(id);
			await auditUser(params);
		}
	}
};
</script>

<style lang="scss" scoped>
.user_form_wrapper {
	width: calc(100% - 10px);
	padding-top: 10px;
}
</style>
<style lang="scss">
.user_role_select {
	.el-select-group__title {
		font-size: 14px;
		font-weight: bold;
		color: #303133;
	}
}
</style>
